package com.reger.test.message.service.impl;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.reger.test.message.dao.MessageMapper;
import com.reger.test.message.model.Message;
import com.reger.test.message.service.MessageService;


@Service
public class MessageServiceImpl implements MessageService {

	private static final Logger log = LoggerFactory.getLogger(MessageServiceImpl.class);

	@Autowired MessageMapper messageMapper;
	
	@Override 
	public void createIfNotExists() {
//		try (HintManager hintManager = HintManager.getInstance()){
			Date now= new Date();
//			hintManager.addDatabaseShardingValue("message", "ctime",now); 
//		}  
		messageMapper.createIfNotExists(D.format(now));
	}

	@Override@Transactional("message")
	public void save(String title, String context) {
		Message message=new Message();
		message.setContext(context);
		message.setTitle(title);
		message.setCtime(new Date());
		int num=messageMapper.insertSelective(message);
		if(num==0){
			log.error("保存消息失败   title:{}, context:{}", title, context);
		}
	}
	@Override@Transactional("message")
	public void saves(List<Message> messages) {
		int num=messageMapper.insertList(messages);
		if(num==0){
			log.error("保存消息失败   messages:{}", messages);
		}
	}

	@Override
	public PageInfo<Message> findAll(int pageNo, int pageSize) {
		PageHelper.startPage(pageNo, pageSize);
//		HintManager hintManager = HintManager.getInstance();
//		hintManager.addDatabaseShardingValue("message", "ctime", new Date());
//		hintManager.addTableShardingValue("message", "ctime", new Date());
		List<Message> page = messageMapper.selectAll();
		return new PageInfo<Message>(page);
	}

}
